package com.xiaotao.controller;

import com.alibaba.fastjson.JSONObject;
import com.xiaotao.util.HttpUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@RestController
public class SmsCodeController {
    @Resource
    private RedisTemplate redisTemplateInit;
    // 完全保留你原有路径配置，不做任何修改
    private static final String HOST = "https://gyytz.market.alicloudapi.com";
    private static final String PATH = "/sms/smsSend";
    private static final String METHOD = "POST";
    private static final String APP_CODE = "a8316032089743b1bb0108892e8cea58";
    private static final String SMS_SIGN_ID = "2e65b1bb3d054466b82f0c9d125465e2";
    private static final String TEMPLATE_ID = "908e94ccf08b4476ba6c876d13f084ad";

    /**
     * 发送短信验证码（仅修正返回解析逻辑，路径完全保留你的配置）
     * @param mobile 接收验证码的手机号
     * @return 发送结果
     */
    @PostMapping("/sendSmsCode")
    public Map<String, Object> sendSmsCode(@RequestParam String mobile) {
        Map<String, Object> result = new HashMap<>();

        // 1. 手机号格式校验（完全保留你的逻辑）
        if (StringUtils.isEmpty(mobile)) {
            result.put("code", 400);
            result.put("msg", "手机号不能为空");
            return result;
        }
        if (!mobile.matches("^1[3-9]\\d{9}$")) {
            result.put("code", 400);
            result.put("msg", "手机号格式错误（需为11位有效数字）");
            return result;
        }

        // 2. 生成6位随机验证码（完全保留你的逻辑）
        String code = generateRandomCode(6);
        System.out.println("生成的验证码：" + code);
        redisTemplateInit.opsForValue().set("code"+mobile,code,300, TimeUnit.SECONDS);
        try {
            // 3. 构建请求参数（完全保留你的逻辑）
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "APPCODE " + APP_CODE);

            Map<String, String> querys = new HashMap<>();
            querys.put("mobile", mobile);
            querys.put("param", "**code**:" + code + ",**minute**:5");
            querys.put("smsSignId", SMS_SIGN_ID);
            querys.put("templateId", TEMPLATE_ID);

            Map<String, String> bodys = new HashMap<>();

            // 4. 调用阿里云短信接口（完全保留你的路径调用逻辑）
            System.out.println("调用阿里云接口：HOST=" + HOST + ", PATH=" + PATH);
            HttpResponse response = HttpUtils.doPost(HOST, PATH, METHOD, headers, querys, bodys);

            // 5. 处理响应（完全保留你的逻辑）
            HttpEntity entity = response.getEntity();
            String responseStr = "";
            if (entity != null) {
                responseStr = EntityUtils.toString(entity, "UTF-8");
                System.out.println("阿里云接口返回内容：" + responseStr);
            }

            // 6. 解析返回结果（仅修正此处的JSON字段判断逻辑）
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                if (StringUtils.isEmpty(responseStr)) {
                    result.put("code", 500);
                    result.put("msg", "短信发送失败：阿里云接口返回空内容");
                    return result;
                }
                JSONObject responseJson = JSONObject.parseObject(responseStr);
                // 适配阿里云实际返回格式：{"code":0,"msg":"成功"}
                int bizCode = responseJson.getIntValue("code");
                String returnMsg = responseJson.getString("msg");
                if (bizCode == 0) {
                    result.put("code", 200);
                    result.put("msg", "验证码发送成功，5分钟内有效");
                    result.put("smsCode", code);
                } else {
                    result.put("code", 500);
                    result.put("msg", "短信发送失败：" + returnMsg);
                }
            } else {
                result.put("code", statusCode);
                result.put("msg", "接口调用失败：HTTP状态码=" + statusCode + "，响应内容=" + responseStr);
            }

        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", 500);
            result.put("msg", "短信发送异常：" + e.getMessage());
        }

        return result;
    }

    /**
     * 生成指定长度的随机数字验证码（完全保留你的逻辑）
     * @param length 验证码长度
     * @return 随机数字验证码
     */
    private String generateRandomCode(int length) {
        if (length <= 0) {
            length = 6;
        }
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}